import request from '@/utils/request'
import axios from 'axios'

// 创建专门用于AI调用的axios实例，设置更长的超时时间
const aiService = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 120000, // 2分钟超时，适合AI生成
  headers: {
    'Content-Type': 'application/json'
  }
})

// 为AI服务添加请求拦截器
aiService.interceptors.request.use(config => {
  // 添加token
  const token = localStorage.getItem('token')
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 为AI服务添加响应拦截器
aiService.interceptors.response.use(res => {
  const code = res.data.code || 200;
  if (code === 200 || code === '0000') {
    return res.data
  } else {
    return Promise.reject(new Error(res.data.msg || 'AI服务响应异常'))
  }
}, error => {
  let message = error.message
  if (message.includes("timeout")) {
    message = "AI生成超时，请稍后重试或尝试简化问题"
  } else if (message.includes("Network Error")) {
    message = "网络连接异常，请检查网络后重试"
  } else if (message.includes("Request failed with status code")) {
    message = "AI服务异常，请稍后重试"
  }
  return Promise.reject(new Error(message))
})

// 生成普通回答 - 使用专门的AI服务实例
export function generateAnswer(model, message) {
  return aiService({
    url: '/api/v1/ollama/generate',
    method: 'get',
    params: {
      model,
      message
    }
  })
}

// 带重试机制的AI调用
export function generateAnswerWithRetry(model, message, maxRetries = 2) {
  return new Promise((resolve, reject) => {
    let retryCount = 0;
    
    const attempt = () => {
      generateAnswer(model, message)
        .then(resolve)
        .catch(error => {
          retryCount++;
          console.log(`AI调用失败，第${retryCount}次重试:`, error.message);
          
          if (retryCount < maxRetries) {
            // 延迟重试，避免立即重试
            setTimeout(attempt, 1000 * retryCount);
          } else {
            reject(error);
          }
        });
    };
    
    attempt();
  });
}

// 流式生成回答
export function generateStreamAnswer(model, message) {
  return request({
    url: '/api/v1/ollama/generate_stream',
    method: 'get',
    params: {
      model,
      message
    },
    responseType: 'stream',
    timeout: 120000 // 2分钟超时
  })
}

// 带 RAG 的流式生成回答 - 修复版本
export function generateStreamRagAnswer(model, ragTag, message) {
  return new Promise((resolve, reject) => {
    // 使用正确的代理路径
    const baseURL = process.env.VUE_APP_BASE_API || '/dev-api';
    const url = `${baseURL}/api/v1/ollama/generate_stream_rag?model=${encodeURIComponent(model)}&ragTag=${encodeURIComponent(ragTag)}&message=${encodeURIComponent(message)}`;

    fetch(url, {
      method: 'GET',
      headers: {
        'Accept': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Authorization': localStorage.getItem('token') ? `Bearer ${localStorage.getItem('token')}` : ''
      }
    })
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        const results = [];

        function readStream() {
          return reader.read().then(({ done, value }) => {
            if (done) {
              resolve(results);
              return;
            }

            const chunk = decoder.decode(value);
            const lines = chunk.split('\n');

            for (const line of lines) {
              if (line.startsWith('data: ')) {
                const data = line.slice(6);
                if (data === '[DONE]') {
                  resolve(results);
                  return;
                }

                try {
                  const parsed = JSON.parse(data);
                  if (parsed.result && parsed.result.output && parsed.result.output.content) {
                    const content = parsed.result.output.content;
                    if (content !== "<think>") {
                      results.push(parsed);
                    }
                  }
                } catch (e) {
                  // 忽略解析错误
                }
              }
            }

            return readStream();
          });
        }

        return readStream();
      })
      .catch(error => {
        reject(error);
      });
  });
}

// 简化的RAG流式调用 - 用于直接处理流
export function generateStreamRagAnswerDirect(model, ragTag, message, options = {}) {
  // 使用正确的代理路径
  const baseURL = process.env.VUE_APP_BASE_API || '/dev-api';
  const url = `${baseURL}/api/v1/ollama/generate_stream_rag?model=${encodeURIComponent(model)}&ragTag=${encodeURIComponent(ragTag)}&message=${encodeURIComponent(message)}`;

  // 支持外部传入 signal
  const fetchOptions = {
    method: 'GET',
    headers: {
      'Accept': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Authorization': localStorage.getItem('token') ? `Bearer ${localStorage.getItem('token')}` : ''
    },
    signal: options.signal || AbortSignal.timeout(300000) // 5分钟超时
  };

  return fetch(url, fetchOptions).then(response => {
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    return response;
  }).catch(error => {
    throw error;
  });
} 